package com.lanou.moving.media;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;

import java.io.IOException;
/**
 * Created by 梁树珍 on 15/10/29.
 */

/**
 * 播放视频的组件
 */
public class MyMediaPlayer extends SurfaceView {
    private MediaPlayer mediaPlayer;//用来控制播放
    private Handler handler;//又来接受从UI线程传来的Handler
    private SurfaceView surfaceView;

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    public MediaPlayer getMediaPlayer() {
        return mediaPlayer;
    }

    public MyMediaPlayer(Context context) {
        super(context);
        initView();
    }

    public MyMediaPlayer(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public void initView() {
        mediaPlayer = new MediaPlayer();
        surfaceView = new SurfaceView(getContext());
        new Thread(new Runnable() {
            @Override
            public void run() {
                //一直获取当前播放的进度
                while (true) {
                    if (mediaPlayer.isPlaying()) {
                        //传递Handler
                        Message msg = new Message();
                        msg.what = 1;//代表刷新UI
                        msg.arg1 = mediaPlayer.getCurrentPosition();
                        handler.sendMessage(msg);
                    }
                }
            }
        }).start();
    }

    public int getMax() {
        return mediaPlayer.getDuration();
    }

    public void setUrl(String url) {
        mediaPlayer.reset();
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.release();
            try {
                mediaPlayer.setDataSource(url);
                mediaPlayer.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
//            mediaPlayer.reset();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setDataSource(url);
            mediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void play() {
        mediaPlayer.setDisplay(getHolder());
        mediaPlayer.start();

    }

    public void pause() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }
    }

    public void stop() {
        mediaPlayer.stop();
    }

    public void seekTo(int progress) {
        mediaPlayer.seekTo(progress);
    }

    public void max(){
        surfaceView.getHolder().setFixedSize(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
}
